import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Search from '@/views/search'
import SearchResult from '@/views/search/result'
import Detail from '@/views/article'
import Edit from '@/views/layout/user/edit'
import Chat from '@/views/layout/user/chat'

// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', // ⭐优先展示在挂载点
    component: Layout,
    // 重定向 到二级路由页面 home
    redirect: '/user',
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          // ⭐只有首页home内的组件被缓存 articleList、ChannelEdit
          isKeepLive: true
        }
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result', // ⭐⭐命名自定 并非二级路由 只是为了方便理解
    component: SearchResult
  },
  {
    path: '/detail/:id', // ⭐需要有动态路由 可以id传值对应不同显示结果
    component: Detail
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// ⭐全局导航守卫拦截未登录(没有token)
// 需要拦截的页面
const loginURL = ['/user', '/qa', '/user/edit']
router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token
  if (token) {
    // 通过
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => item === to.path)) {
      // 判断成立的页面需要登录
      // next('/login') // 跳转但有路由故障报错 Redirected
      // router.push('/login') 路径写死 无登录回退功能
      // 12/04/am⭐⭐添加 跳转去的页面需要登录 跳转到登录页面登录成功后又回到之前需要去但没去成功的页面  登录回退功能
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
